import express from 'express';
import {
  registerDevice,
  deleteDevice,
  getDevices,
  getDevice,
  updateDevice,
  updateDevicePassword,
  getDeviceData,
  saveDeviceData,
  sendCommand,
  updateFirmware,
  upload,
  getDeviceConfig,
  updateDeviceConfig,
  sendBinaryFile,
} from '../controllers/deviceController';
import mqttService from '../services/mqttService';
import { authMiddleware } from '../middleware/auth.middleware';

const router = express.Router();

// 所有设备路由都需要认证
router.use(authMiddleware.authenticate);

// 设备管理路由
router.post('/', registerDevice);
router.get('/', getDevices);
router.get('/stats', async (req, res) => {
  try {
    const userId = req.user._id;
    const stats = await mqttService.getDeviceStats(userId.toString());
    res.json(stats);
  } catch (error) {
    res.status(500).json({ message: '获取设备统计信息失败' });
  }
});
router.get('/:deviceId', getDevice);
router.put('/:deviceId', updateDevice);
router.put('/:deviceId/password', updateDevicePassword);
router.delete('/:deviceId', deleteDevice);

// 设备数据路由
router.get('/:deviceId/data', getDeviceData);
router.post('/:deviceId/data', saveDeviceData);

// 设备命令路由
router.post('/:deviceId/command', sendCommand);

// 更新固件
router.post('/:deviceId/firmware', upload.single('firmware'), updateFirmware);

// 设备配置路由
router.get('/:deviceId/config', getDeviceConfig);
router.put('/:deviceId/config', updateDeviceConfig);

// 文件传输路由
router.post('/:deviceId/file', upload.single('file'), sendBinaryFile);

export default router; 